#!/bin/bash

PACKAGE_NAME='go-todo'
APP_NAME='todo'
EXPOSE_PORT=9401
RPC_PORT=9402
WEBSOCKET_PORT=9403
GIN_MODE=release

echo "1.生成镜像";
sudo docker build -f Dockerfile  -t ${PACKAGE_NAME}:${PACKAGE_NAME} .

echo "2.因为磁盘空间有限,所以删掉中间镜像";
sudo docker image prune --force --filter "label=stage=builder_${APP_NAME}"

echo "3.删除现有该镜像的容器" + ${PACKAGE_NAME};
CONTRAINERID=$(sudo docker ps -a -q --filter name=${PACKAGE_NAME})
echo "${CONTRAINERID}"
if [ -n "${CONTRAINERID}" ]; then
  sudo docker rm -f ${CONTRAINERID}
fi

echo "5.运行该镜像的容器";

sudo docker run -d \
    -p ${EXPOSE_PORT}:${EXPOSE_PORT} \
    -p ${RPC_PORT}:${RPC_PORT} \
    -p ${WEBSOCKET_PORT}:${WEBSOCKET_PORT} \
    -v ${PWD}/logs:/home/work/${APP_NAME}/logs \
    --restart=always \
    -e "SERVICE_NAME=${PACKAGE_NAME}" \
    -e "SERVICE_TAGS=golang,backend,${APP_NAME}" \
    -e "SERVICE_CHECK_HTTP=/${APP_NAME}/metrics" \
    -e "SERVICE_CHECK_INTERVAL=5s" \
    -e "QMP_SERVICE_NAME=${APP_NAME}" \
    -e "GIN_MODE=${GIN_MODE}" \
    --name ${PACKAGE_NAME} \
    --network qtable \
    ${PACKAGE_NAME}:${PACKAGE_NAME} --log ${APP_NAME}

echo "5.收尾删掉老的悬空镜像";
# 新的image内容后:执行完前边的build命令后,新生成的镜像会占据老Image的tag。而老image并不会消失,只是tag变为None而已。
# 老image此时依旧有关联的container在运行，只有在执行完步骤3后才算是将之真正变成悬空镜像，此时就可以用prune来删除了.
sudo docker image prune --force --filter "label=stage=stable_${APP_NAME}"
#清除超过创建时间超过2小时的镜像
sudo docker image prune --force --filter "until=2h"